package com.oscar.ehome.view.teamview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.teamBean.CusourTeamBean;
import com.oscar.ehome.bean.teamBean.TeamListBean;
import com.oscar.ehome.bean.teamBean.UserAppInfoBean;
import com.oscar.ehome.bean.teamBean.UserRoleStaticBean;
import com.oscar.ehome.bean.teamBean.UserStartStaticBean;
import com.oscar.ehome.presenter.TeamPresenter;
import com.oscar.ehome.provider.teamlist.WordsNavigation;
import com.oscar.ehome.utils.spinerpopwindow.AbstractSpinerAdapter;
import com.oscar.ehome.utils.spinerpopwindow.SpinerPopWindow;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.teamview.adapter.TeamAdapter;
import com.oscar.ehome.view.teamview.view.TeamListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/7/19
 * 团队列表页
 */

public class TeamListActivity extends BasesActivity<TeamListView, TeamPresenter> implements TeamListView, AbstractSpinerAdapter.IOnItemSelectListener,
        TeamAdapter.IntentListener, WordsNavigation.onWordsChangeListener, AbsListView.OnScrollListener, ProgressFrameLayout.AgainRequestListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 选择框
     */
    @BindView(R.id.img_spinner)
    ImageView imgSpinner;
    /**
     * 标题
     */
    @BindView(R.id.liear_title)
    LinearLayout liearTitle;
    /**
     * 统计图
     */
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    /**
     * 标题
     */
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;
    /**
     * 团队列表
     */
    @BindView(R.id.teamlistview)
    ListView teamlistview;
    /**
     * 通讯录列表
     */
    @BindView(R.id.hintBar)
    WordsNavigation word;
    /**
     * 通讯录索引
     */
    @BindView(R.id.teamlist_tv)
    TextView teamlisttv;
    /**
     *
     */
    @BindView(R.id.teamlist_fragment)
    FrameLayout teamlistFragment;
    /**
     * 无网络布局
     */
    @BindView(R.id.teamlists_fragment)
    ProgressFrameLayout teamlistsFragment;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    //adapter
    private TeamAdapter mAdapter;
    //请求数据
    TeamPresenter teamPresenter;


    //我的团队
    private List<String> nameList = new ArrayList<String>();
    //团队列表
    List<TeamListBean.ListBean> mDatas = new ArrayList<>();
    //排序后的团队列表
    List<TeamListBean.ListBean> mDatas_list = new ArrayList<>();
    //排序的列表
    List<CusourTeamBean> list = new ArrayList<>();
    //筛选框
    SpinerPopWindow mSpinerPopWindow;
    String id = "";//个人ID
    String ids = "";//职级id
    String name = "";//姓名
    int chaungtuan = 0;//是不是创团过来的
    private Handler handler;
    int chaun = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teamlist);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(TeamListActivity.this).getSystemConfig().getColor()));
        initView();
        initData();
        onClicks();
    }

    @Override
    protected TeamPresenter createPresenter() {
        teamPresenter = new TeamPresenter(this);
        return teamPresenter;
    }

    /**
     * 初始化view
     */
    private void initView() {
        id = getIntent().getStringExtra("id");
        ids = getIntent().getStringExtra("ids");
        name = getIntent().getStringExtra("name");
        chaungtuan = getIntent().getIntExtra("chaungtuan", 0);
        chaun = getIntent().getIntExtra("chaun", 0);
        if (chaungtuan == 1) {//创团过来的不需要显示统计图。
            titleImgRight.setVisibility(View.GONE);
            titleRightLayput.setVisibility(View.GONE);
        } else {
            titleRightLayput.setVisibility(View.VISIBLE);
            titleImgRight.setVisibility(View.VISIBLE);
            titleImgRight.setImageResource(R.mipmap.zhiji);
        }
        if (chaun == 1) {//职级
            titleTopbar.setText(name);
            imgSpinner.setVisibility(View.GONE);
        } else if (chaun == 3) {//星级
            switch (name) {
                case "0":
                    titleTopbar.setText("零星");
                    break;
                case "1":
                    titleTopbar.setText("一星");
                    break;
                case "2":
                    titleTopbar.setText("二星");
                    break;
                case "3":
                    titleTopbar.setText("三星");
                    break;
            }
            imgSpinner.setVisibility(View.GONE);
        } else if (chaun == 2) {
            titleTopbar.setText(name + "的团队");
            imgSpinner.setVisibility(View.VISIBLE);
        }

        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);

        nameList.add(name + "的全部下级");
        nameList.add(name + "的直属下级");
        mSpinerPopWindow = new SpinerPopWindow(this);
        mSpinerPopWindow.refreshData(nameList, 0);

    }

    /**
     * 绑定点击事件
     */
    private void onClick() {

        //设置列表点击滑动监听
        handler = new Handler();
        word.setOnWordsChangeListener(this);
        teamlistview.setOnScrollListener(this);
        mAdapter.setOnINtentClickListener(this);

    }

    public void onClicks() {
        mSpinerPopWindow.setItemListener(this);
        teamlistsFragment.setAgainRequestListener(this);
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(TeamListActivity.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            teamlistsFragment.stopRefresh();
            teamlistFragment.setVisibility(View.VISIBLE);
            switch (chaun) {
                case 1://查看职级下的人员
                    teamPresenter.getReoalList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(), id, ids);
                    showLoading();
                    break;
                case 2:
                    teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(),
                            id, "1");
                    showLoading();
                    break;
                case 3://查看星级下的人员
                    teamPresenter.getStartList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(), id, ids);
                    showLoading();
                    break;
            }
        } else {
            teamlistFragment.setVisibility(View.GONE);
            teamlistsFragment.setVisibility(View.VISIBLE);
            teamlistsFragment.setLoadFail();
        }
    }

    /**
     * 排序
     *
     * @param mDatas
     */
    public void setListBean(List<TeamListBean.ListBean> mDatas) {
        list = new ArrayList<>();
        mDatas_list = new ArrayList<>();
        for (int i = 0; i < mDatas.size(); i++) {
            list.add(new CusourTeamBean(mDatas.get(i).getName()));
        }
        //对集合排序
        Collections.sort(list, new Comparator<CusourTeamBean>() {
            @Override
            public int compare(CusourTeamBean o1, CusourTeamBean o2) {
                return o1.getPinyin().compareTo(o2.getPinyin());
            }
        });

        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            for (int j = 0; j < mDatas.size(); j++) {
                String names = mDatas.get(j).getName();
                if (name.equals(mDatas.get(j).getName())) {
                    mDatas_list.add(mDatas.get(j));
                    break;
                }
            }
        }
    }

    @OnClick({R.id.title_layout_left, R.id.title_right_layput, R.id.liear_title})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_right_layput://统计图
                if (mDatas.size() > 0) {
                    Intent intent = new Intent(this, TeamCountViewActivity.class);
                    intent.putExtra("member_name", name);
                    intent.putExtra("id", id);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.show(TeamListActivity.this, "团队暂无人员");
                }
                break;
            case R.id.liear_title://标题筛选
                if (chaun == 2) {
                    mSpinerPopWindow.showAsDropDown(liearTitle, 0, 40);
                }
                break;
            case R.id.title_layout_left://返回
                finish();
                break;
        }
    }

    /**
     * 统计
     *
     * @param TeamListBean
     */
    @Override
    public void LoadUserTeamAppList(TeamListBean TeamListBean) {
        dismissLoading();
        mDatas = new ArrayList<>();
        mDatas = TeamListBean.getList();
        if (mDatas.size() > 0) {
            setListBean(mDatas);
            mAdapter = new TeamAdapter(TeamListActivity.this, mDatas_list, list);
            teamlistview.setAdapter(mAdapter);
            onClick();
        } else {
            teamlistFragment.setVisibility(View.GONE);
            teamlistsFragment.setNoResult();
        }
    }

    @Override
    public void getRoalList(TeamListBean TeamListBean) {
        dismissLoading();
        mDatas = new ArrayList<>();
        mDatas = TeamListBean.getList();
        if (mDatas.size() > 0) {
            setListBean(mDatas);
            mAdapter = new TeamAdapter(TeamListActivity.this, mDatas_list, list);
            teamlistview.setAdapter(mAdapter);

            onClick();
        } else {
            teamlistFragment.setVisibility(View.GONE);
            teamlistsFragment.setNoResult();
        }
    }

    @Override
    public void getStartLeves(TeamListBean TeamListBean) {
        dismissLoading();
        mDatas = new ArrayList<>();
        mDatas = TeamListBean.getList();
        if (mDatas.size() > 0) {
            setListBean(mDatas);
            mAdapter = new TeamAdapter(TeamListActivity.this, mDatas_list, list);
            teamlistview.setAdapter(mAdapter);

            onClick();
        } else {
            teamlistFragment.setVisibility(View.GONE);
            teamlistsFragment.setNoResult();
        }
    }

    @Override
    public void LoadUserRoleStatisticsAppList(UserRoleStaticBean userRoleStaticBean) {

    }

    @Override
    public void LoadUserStartStatisticsAppList(UserStartStaticBean userRoleStaticBean) {

    }

    @Override
    public void LoadUserAppInfo(UserAppInfoBean userAppInfoBean) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }

    /**
     * 筛选团队列表
     *
     * @param pos
     */
    @Override
    public void onItemClick(int pos) {
        setHero(pos);
    }

    /**
     * 筛选团队列表
     *
     * @param pos
     */
    private void setHero(int pos) {
        if (pos >= 0 && pos <= nameList.size()) {
            String value = nameList.get(pos);
            titleTopbar.setText(value);
            if (pos == 0) {
                teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(),
                        id, "1");
                showLoading();

            } else {
                teamPresenter.LoadUserTeamAppList(SystemConfigFactory.getInstance(this).getSystemConfig().getToken(),
                        id, "2");
                showLoading();
            }
        }
    }

    @Override
    public void onIntentClick(int postion, int team_type) {
        if (team_type == 1) {//个人团队页
            if (!mDatas_list.get(postion).getChildNum().equals("0") && !mDatas_list.get(postion).getAllChildNum().equals("0")) {
                chaun = 2;
                id = mDatas_list.get(postion).getId();
                name = mDatas_list.get(postion).getName();
                titleTopbar.setText(name + "的团队");
                imgSpinner.setVisibility(View.VISIBLE);
                titleRightLayput.setVisibility(View.VISIBLE);
                titleImgRight.setVisibility(View.VISIBLE);
                titleImgRight.setImageResource(R.mipmap.zhiji);
                initData();
            } else {
                ToastUtil.show(TeamListActivity.this, R.string.nodatamesage);
            }
        } else if (team_type == 2) {//个人信息页
            Intent intent = new Intent(this, TeamDetailActivity.class);
            intent.putExtra("id", mDatas_list.get(postion).getId());
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //当滑动列表的时候，更新右侧字母列表的选中状态
        word.setTouchIndex(list.get(firstVisibleItem).getHeaderWord());
    }

    @Override
    public void wordsChange(String words) {
        updateWord(words);
        updateListView(words);
    }

    /**
     * @param words 首字母
     */
    private void updateListView(String words) {
        for (int i = 0; i < list.size(); i++) {
            String headerWord = list.get(i).getHeaderWord();
            //将手指按下的字母与列表中相同字母开头的项找出来
            if (words.equals(headerWord)) {
                //将列表选中哪一个
                teamlistview.setSelection(i);
                //找到开头的一个即可
                return;
            }
        }
    }

    /**
     * 更新中央的字母提示
     *
     * @param words 首字母
     */
    private void updateWord(String words) {
        teamlisttv.setText(words);
        teamlisttv.setVisibility(View.VISIBLE);
        //清空之前的所有消息
        handler.removeCallbacksAndMessages(null);
        //1s后让tv隐藏
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                teamlisttv.setVisibility(View.GONE);
            }
        }, 500);
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(TeamListActivity.this, R.string.pull_to_refresh_network_error);
        }
    }
}
